package com.alm.token.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alm.token.ConStant;
import com.alm.token.GlideApp;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.base.BaseAdapter;
import com.alm.token.common.RefreshLoadMoreManager;
import com.alm.token.ui.data.bean.ActivityDetailData;
import com.alm.token.ui.data.bean.ActivityIndexData;
import com.alm.token.ui.data.bean.ActivityJoinListData;
import com.alm.token.ui.data.bean.G12CanData;
import com.alm.token.ui.data.bean.RegisterData;
import com.alm.token.ui.data.bean.UserListLHData;
import com.alm.token.ui.data.bean.UserWalletData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.ui.view.ActivityView;
import com.alm.token.ui.view.QuantitativeOrderOpenAddView;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.EmptyUtils;
import com.chad.library.adapter.base.BaseViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import baibeiwallet.event.RefreshActivityEvent;
import baibeiwallet.utils.DialogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ActivityRegistrationRecordActivity extends BaseActivity implements ActivityView<Object> {
    @BindView(R.id.leftItem)
    ImageView leftItem;
    @BindView(R.id.centerItem)
    TextView centerItem;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.tv_clickreload)
    TextView tvClickreload;
    @BindView(R.id.nodatashow_body)
    RelativeLayout nodatashowBody;

    private RefreshLoadMoreManager<ActivityJoinListData.DataBeanX.DataBean> manager;
    private List<ActivityJoinListData.DataBeanX.DataBean> dataBeans = new ArrayList<>(), dataBeanListold = new ArrayList<>();

    private int limit = 100, page = 1;
    private boolean isfull = false;

    @Override
    protected MyPreenter initPreenter() {
        return new MyPreenter(this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_activitelist;
    }

    @Override
    protected void initVariables() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void initViews() {
        new ActionBarHelper(this).setTitle(getString(R.string.tv_hint_activity_order_title));
        initManager();
        swipeRefreshLayout.setVisibility(View.GONE);
        nodatashowBody.setVisibility(View.VISIBLE);
    }

    private void initManager() {
        ActivityListAdapter adapter = new ActivityListAdapter(this, new Onclick1() {
            @Override
            public void click1Listener(ActivityJoinListData.DataBeanX.DataBean item) {

                UserWalletData.DataBean.SysMsgBean sysMsgBean = new UserWalletData.DataBean.SysMsgBean();
                sysMsgBean.setTitle(getString(R.string.tv_hint_activity_order_applycancle));
                sysMsgBean.setContent(getString(R.string.tv_hint_activity_order_applycancle_warm));
                DialogUtils.showInfor1(ActivityRegistrationRecordActivity.this, sysMsgBean, (pwd) -> {
                    preenter.getActivitycancelOrderData(item.getId() + "");
                });
            }
        });
        manager = new RefreshLoadMoreManager.Builder(this)
                .setAdapter(adapter)
                .setRecyclerView(recyclerView)
                .setOnListItemClickListener(new RefreshLoadMoreManager.OnListItemClickListener() {
                    @Override
                    public void onListItemClick(BaseAdapter.BaseItem item, int position) {
                        if (dataBeans != null && dataBeans.size() > position) {
                            Intent intent = new Intent(ActivityRegistrationRecordActivity.this, ActivityConfirmationActivity.class);

//                            if (dataBeans.get(position).getStatus() == 2 || dataBeans.get(position).getStatus() == 4) {
//                                intent = new Intent(ActivityRegistrationRecordActivity.this, ActivityConfirmationActivity.class);
//                            }else {
//                                intent = new Intent(ActivityRegistrationRecordActivity.this, ActivityDeatailActivity.class);
//                            }
//                            ActivityIndexData.DataBean dataBean = new ActivityIndexData.DataBean();
//                            dataBean.setId(dataBeans.get(position).getActivity().getId());
                            intent.putExtra("databean", dataBeans.get(position));
                            startActivity(intent);
                        }
                    }
                })
                .setSwipeRefreshLayout(swipeRefreshLayout)
                .setOnRefreshListener(new RefreshLoadMoreManager.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
//                        showToast("onRefresh");
                        swipeRefreshLayout.setRefreshing(false);
                        loadData();
                    }
                })

                .setOpenLoadMore(true)
                .setOnLoadMoreListener(new RefreshLoadMoreManager.OnLoadMoreListener() {
                    @Override
                    public void onLoadMore() {
                        manager.getAdapter().loadMoreEnd(true);
                        manager.getAdapter().loadMoreFail();
                        showWaitDialog();
                        preenter.getActivityJoinListData(String.valueOf(limit), String.valueOf(page));
                    }
                })
                .build();
        recyclerView.setNestedScrollingEnabled(false);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshActivityEvent(RefreshActivityEvent refreshActivityEvent) {
        preenter.getActivityJoinListData(String.valueOf(limit), String.valueOf(page));
    }

    @Override
    protected void loadData() {
        limit = 100;
        page = 1;
        preenter.getActivityJoinListData(String.valueOf(limit), String.valueOf(page));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.open_btn:
//                startActivityForResult(QuantitativeOrderOpenAddActivity.class, ActivityForResultCode);
//                break;
//            case R.id.rightItem:
//                startActivity(QuantitativeOrderCloseListActivity.class);
//                break;

//            case R.id.open_supervip:
//                //解除 查询 当期vip订单
//                Intent intent = new Intent(ActivityListActivity.this, VipApplyActivity.class);
//                intent.putExtra("intentType", 1);
//                startActivity(intent);
//                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == ActivityForResultCode) {
//            if (resultCode == QuantitativeOrderOpenAddActivity.AddAppendSucc) {
////                showToast("添加成功，刷新列表");
//                loadData();
//            }
//            if (resultCode == QuantitativeOrderDetailActivity.AppendSucc) {
////                showToast("添加成功，刷新列表");
//                loadData();
//            }
//        }
    }

    @Override
    public void getData(Object o) {

    }

    @Override
    public void getActivityIndexData(ActivityIndexData activityIndexData) {

    }

    @Override
    public void getActivityDetailData(ActivityDetailData activityDetailData) {

    }

    @Override
    public void getActivityJoinData(RegisterData registerData) {

    }

    @Override
    public void getActivityPayOrderData(RegisterData registerData) {
        showToast(registerData.getMsg());
        if (registerData.getStatus() == 0) {
            loadData();
        }
    }

    @Override
    public void getActivityJoinListData(ActivityJoinListData activityJoinListData) {


        if (activityJoinListData.getStatus() == 0 && activityJoinListData.getData() != null && activityJoinListData.getData().getData() != null) {
            if (page == 1) {
                dataBeans.clear();
            } else if (!isfull && dataBeans.size() > (page - 1) * 100) {
                dataBeans.removeAll(dataBeanListold);
            }
//            dataBeanList.clear();
            if (activityJoinListData.getData().getData().size() == 100) {
                isfull = true;
                page = page + 1;
            } else {
                isfull = false;
            }

            dataBeanListold = activityJoinListData.getData().getData();
            dataBeans.addAll(activityJoinListData.getData().getData());
            for (int i = 0; i < dataBeans.size(); i++) {
                dataBeans.get(i).setLayoutId(ActivityListAdapter.LAYOUT_ID);
            }
            manager.setData(dataBeans);
        } else {
            showToast(activityJoinListData.getMsg());
        }

        if (dataBeans.size() == 0) {
            swipeRefreshLayout.setVisibility(View.GONE);
            nodatashowBody.setVisibility(View.VISIBLE);
        } else {
            swipeRefreshLayout.setVisibility(View.VISIBLE);
            nodatashowBody.setVisibility(View.GONE);
        }
    }

    @Override
    public void getCode(RegisterData registerData) {

    }

    @Override
    public void jumpToLoginAct(int staue) {
        if (staue == 3) {
//            showToast(getString(R.string.common_relogin));
//            Intent intent = new Intent();
//            intent.setAction(ConStant.EXIT_APP);
//            sendBroadcast(intent);
//            startActivity(BlockWalletLoginActivity.class);
//            finish();
        } else if (staue == 4) {
//            showToast(getString(R.string.paypasw_hint_setpaypsw));
//            Intent intent = new Intent(getActivity(),PayPwdActivity.class);
//            intent.putExtra("PayPwdActivityType",PayPwdActivity.PAYPSW_SET);
//            startActivity(intent);
//            getActivity().finish();
            showToSetPaypswDialog();
        } else if (staue == 666) {
            showToUpdata();
        }
    }

    @Override
    public void onError(String error) {
        showToast(getString(R.string.common_loaderrritry));
    }

    @Override
    public void ShowProgress() {

        showWaitDialog();
    }

    @Override
    public void hideProgress() {
        hideWaitDialog();
    }


//    @Override
//    public void getUserListLHData(Object userListLHData) {
//
//        if (userListLHData instanceof UserListLHData) {
//            UserListLHData data = (UserListLHData) userListLHData;
//            if (data.getStatus() == 0 && data.getData() != null) {
//                dataBeans.clear();
//                dataBeansGuanbi.clear();
//                dataBeansJinxing.clear();
//                dataBeans.addAll(data.getData());
//
//                for (int i = 0; i < dataBeans.size(); i++) {
//                    dataBeans.get(i).setLayoutId(ActivityListAdapter.LAYOUT_ID);
//                    if (Integer.parseInt(dataBeans.get(i).getOrderStatus()) != 0) {
//                        dataBeansGuanbi.add(dataBeans.get(i));
//                    } else {
//                        dataBeansJinxing.add(dataBeans.get(i));
//                    }
//                }
//                MyApp.setDataBeansGuanbi(dataBeansGuanbi);
//                manager.setData(dataBeans);
//            } else showToast(data.getMsg());
//        }
//
//        if (dataBeans.size() == 0) {
//            swipeRefreshLayout.setVisibility(View.GONE);
//            nodatashowBody.setVisibility(View.VISIBLE);
//        } else {
//            swipeRefreshLayout.setVisibility(View.VISIBLE);
//            nodatashowBody.setVisibility(View.GONE);
//        }
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.tv_clickreload)
    public void onViewClicked() {
        loadData();
    }

    public class ActivityListAdapter extends BaseAdapter<ActivityJoinListData.DataBeanX.DataBean> {

        public static final int LAYOUT_ID = R.layout.item_activity_joinlist;

        public Onclick1 onclick;

        public ActivityListAdapter(@NonNull Context context, Onclick1 onclick) {
            super(context);
            this.onclick = onclick;
        }

        @Override
        protected void convert(BaseViewHolder helper, ActivityJoinListData.DataBeanX.DataBean item, int itemType) {
            /**
             * id : 1
             * userId : 1627
             * userRealNameEn : 用户真实英文姓名
             * userRealName : 真实姓名
             * phoneAreaCode : 86
             * userPhone : 17968455
             * nationality : 中国
             * userSex : 1
             * userBirthPlace : 出生地
             * userBirthTime : 2019-06-05
             * passportNo : 护照号
             * passportCreateTime : 2019-06-05
             * passportEndTime : 2019-06-05
             * passportAddress : 护照地址
             * msg : 备注
             * orderId : 1
             * status : 3
             * createTime : 1560325284000
             * payTime : 1560325284000
             * updateTime : null
             * lastPayTime : null
             * orderSn :
             * city : 城市
             * activity : {"id":1,"title":"特使","img":"http://psm8zx75e.bkt.clouddn.com/1e9d038c7e500a8f52bc4928956f521.png","detailImg":"http://psm8zx75e.bkt.clouddn.com/3a860ddfd773dffde2556039948f164.png","price":15,"moneyType":1,"country":"","city":"","address":"测试的地址","status":1,"startTime":1560147843000,"endTime":1561271050000,"createTime":1559802255000,"updateTime":1560322873000,"content":"活动内容","contentEn":"activity content","readNum":0,"moneyTypeName":"ETH","moneyTypeImg":"http://file.gufang.co/eth_img.png"}
             */

            //设置图片圆角角度
//            RoundedCorners roundedCorners= new RoundedCorners(12);
            //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
//            RequestOptions options=RequestOptions.bitmapTransform(roundedCorners) ;.apply(options)
            ActivityJoinListData.DataBeanX.DataBean.ActivityBean activityBean = item.getActivity();

            ImageView imageView = helper.getView(R.id.img_activity_detail_ordertopimg);
            GlideApp.with(context).load(activityBean.getImg()).into(imageView);

            ImageView imgWalletView = helper.getView(R.id.img_activity_list_expend);
            GlideApp.with(context).load(activityBean.getMoneyTypeImg()).into(imgWalletView);

            helper.setText(R.id.tv_activity_detail_ordert_id, getString(R.string.tv_hint_activity_order_noid, item.getOrderSn()));
            helper.setText(R.id.tv_activity_detail_ordert_title, activityBean.getTitle());
            helper.setText(R.id.tv_activity_list_time, CommonUtil.getDateTimeFromMillisecond1(activityBean.getStartTime()) + "~" + CommonUtil.getDateTimeFromMillisecond1(activityBean.getEndTime()));
            helper.setText(R.id.tv_activity_list_locial, activityBean.getCountry() + item.getCity());
            helper.setText(R.id.tv_activity_list_expend, activityBean.getPrice() + activityBean.getMoneyTypeName());
//            helper.setText(R.id.tv_activity_list_expend, activityBean.getPrice() + " $");
            // 订单状态 2 待支付 3已报名 4 支付失败 5 退回 6 超时 7 取消
            helper.setText(R.id.tv_activity_list_staue, item.getStatus() == 2 ? getString(R.string.tv_hint_activity_order_staue_paywait) : item.getStatus() == 3 ? getString(R.string.tv_hint_activity_order_staue_paysucc) :
                    item.getStatus() == 4 ? getString(R.string.tv_hint_activity_order_staue_payout) : item.getStatus() == 5 ? getString(R.string.tv_hint_activity_order_staue_payout) : item.getStatus() == 6 ? getString(R.string.tv_hint_activity_order_staue_payout) : getString(R.string.tv_hint_activity_order_staue_payout));// 状态 1 开启 0 关闭
            helper.setTextColor(R.id.tv_activity_list_staue, getResources().getColor((item.getStatus() == 3 || item.getStatus() == 2 || item.getStatus() == 4) ? R.color.colorgreen : R.color.colorPrimary444444));
            helper.setImageDrawable(R.id.img_activity_list_staue, getResources().getDrawable((item.getStatus() == 3 || item.getStatus() == 2 || item.getStatus() == 4) ? R.drawable.icon_activity_list_openstaue : R.drawable.icon_activity_list_closestaue));

            if (item.getStatus() == 2 || item.getStatus() == 6) {
                helper.setVisible(R.id.tv_activity_list_applycancle, true);
                helper.setOnClickListener(R.id.tv_activity_list_applycancle, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (EmptyUtils.isNotEmpty(onclick)) {
                            onclick.click1Listener(item);
                        }
                    }
                });
            } else {
                helper.setVisible(R.id.tv_activity_list_applycancle, false);
                helper.setOnClickListener(R.id.tv_activity_list_applycancle, null);
            }


        }


    }

    public interface Onclick1 {
        void click1Listener(ActivityJoinListData.DataBeanX.DataBean item);
    }
}
